// We are using an oversampling and averaging method to increase the ADC resolution
// We take 16 samples so the theorical ADC resolution is now 12 bits.
// ADC clock is 250Khz so with 6 channels maximum bandwidth is 100Hz.
// Reading tested at 166Hz (so bandwidth of 83Hz)
// With 1 sample accuracy is around +- 3 ADC steps
// With 16 samples accuracy is around +- 6 ADC steps
void Read_adc_raw(void)
{
  unsigned int temp;    

  for (int i=0 ; i<6 ; i++)
  {
    do{
      temp = AN_raw[sensors[i]];             // sensors[] maps sensors to correct order 
    } 
    while(temp != AN_raw[sensors[i]]);  // Check if there was an ADC interrupt during readings...

    AN[i] = temp;
  }
}

// Read the ADC (remove the offset and set the right sign)
// Throw out nonsensical values
int read_adc(byte select)
{
  return SENSOR_SIGN[select]*(AN[select]-AN_OFFSET[select]);
}

// Activating the ADC interrupts
void Analog_Init(void)
{
  // Set prescaler to 64, so ADC clock is now 250 KHz
  bitSet(ADCSRA, ADPS2);
  bitSet(ADCSRA, ADPS1);
  bitClear(ADCSRA, ADPS0);

  ADCSRA|=(1<<ADIE)|(1<<ADEN); // Enable interrupt and enable ADC
  ADCSRA|= (1<<ADSC);  // Start the conversion
}

// Set the ADC reference voltage
void Analog_Reference(byte mode)
{
  analog_reference = mode;
}

//ADC interrupt vector, this piece of code
//is executed everytime a convertion is done. 

//envoi des données toutes les 6.5 ms => 154 Hz
//envoi des données toutes les 6.7 ms => 149 Hz sans envois
//135Hz at 38400 bps (107hz with matlab)
//145Hz at 115200 bps (140hz with matlab)
//160Hz with matlab at 115200 bps with serialbuf
ISR(ADC_vect)
{
  volatile uint8_t low, high;
  low = ADCL;
  high = ADCH;

  analog_buffer[MuxSel] += (high << 8) | low;   // Cumulate analog values
  analog_count[MuxSel]++;

  if(analog_count[MuxSel] == 16) {  // Read 16 samples
    AN_raw[MuxSel] = analog_buffer[MuxSel];
    analog_buffer[MuxSel] = 0;
    analog_count[MuxSel] = 0;
    if (MuxSel == 7 ) { //on a lu le dernier adc
      //ttemp_old = ttemp;
      //ttemp = micros();
      Read_adc_raw();
      printdata(); //on retourne les valeurs sur le serial
    }
  }

  MuxSel++;  //next channel
  //we need to read channels 0,1,2,3,6,7
  if(MuxSel == 4)
    MuxSel = 6;
  MuxSel &= 0x07;   //if(MuxSel >=8) MuxSel=0;

  ADMUX = (analog_reference << 6) | MuxSel;  // Select channel MuxSel
  ADCSRA|= (1<<ADSC);  // Start the conversion
}












